package com.onlyxiahui.common.lib.util.http;

import java.security.cert.Certificate;
import java.util.Collections;
import java.util.Map;

import javax.net.ssl.SSLSession;

import org.apache.http.HttpResponseInterceptor;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ManagedHttpClientConnection;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpCoreContext;

/**
 * Description <br>
 * Date 2021-01-25 11:48:08<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class HttpClient4CertificateUtil {

	// 原文出自【易百教程】，商业转载请联系作者获得授权，非商业请保留原文链接：https://www.yiibai.com/httpclient/httpclient-get-server-certificates.html
	public static final String PEER_CERTIFICATES = "PEER_CERTIFICATES";

	// create http response certificate interceptor
	static HttpResponseInterceptor certificateInterceptor = (httpResponse, context) -> {
		ManagedHttpClientConnection routedConnection = (ManagedHttpClientConnection) context.getAttribute(HttpCoreContext.HTTP_CONNECTION);
		SSLSession sslSession = routedConnection.getSSLSession();
		if (sslSession != null) {

			// get the server certificates from the {@Link SSLSession}
			Certificate[] certificates = sslSession.getPeerCertificates();

			// add the certificates to the context, where we can later grab it from
			context.setAttribute(PEER_CERTIFICATES, certificates);
		}
	};
	// create closable http client and assign the certificate interceptor
	// static CloseableHttpClient httpClient =
	// HttpClients.custom().addInterceptorLast(certificateInterceptor).build();

	static HttpClientPoolingAdaptor hcpa = new HttpClientPoolingAdaptor() {
		public void custom(HttpClientBuilder httpClientBuilder) {
			httpClientBuilder.addInterceptorLast(certificateInterceptor);
		}
	};

	public static Certificate[] doPost(String url, String body) {
		return doPost(url, Collections.emptyMap(), body, null, null);
	}

	public static Certificate[] doPost(String url,
			Map<String, String> headers,
			Map<String, Object> params,
			String requestCharset,
			String responseCharset) {
		HttpPost httpPost = new HttpPost(url);
		// 配置请求headers
		hcpa.setHeaders(httpPost, headers);
		// 配置请求参数
		hcpa.setParameters(null, httpPost, params, requestCharset);
		return execute(httpPost, responseCharset);

	}

	public static Certificate[] doPost(
			String url,
			Map<String, String> headers,
			String body,
			String requestCharset,
			String responseCharset) {

		if (null == (url) || url.isEmpty()) {
			return null;
		}

		HttpPost httpPost = new HttpPost(url);
		// 配置请求headers
		hcpa.setHeaders(httpPost, headers);
		// 配置请求参数
		hcpa.setBody(httpPost, body, requestCharset);
		return execute(httpPost, responseCharset);
	}

	public static Certificate[] execute(HttpPost httpPost, String responseCharset) {
		Certificate[] peerCertificates = null;
		try {

			// make HTTP GET request to resource server
//			HttpGet httpget = new HttpGet("https://www.baidu.com");
//			System.out.println("Executing request " + httpget.getRequestLine());
			CloseableHttpClient httpClient = hcpa.getHttpClient();
			// create http context where the certificate will be added
			HttpContext context = new BasicHttpContext();
			httpClient.execute(httpPost, context);

			// obtain the server certificates from the context
			peerCertificates = (Certificate[]) context.getAttribute(PEER_CERTIFICATES);

			// loop over certificates and print meta-data
//			for (Certificate certificate : peerCertificates) {
//				X509Certificate real = (X509Certificate) certificate;
//			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return peerCertificates;
	}
}
